#!/usr/bin/env python
import htmllib
import formatter
import urllib
import re
import datetime
class BlogParser(htmllib.HTMLParser):
    is_author=False
    is_date=False
    is_time=False
    is_category=False
    is_content=False
    content=''
    title=''
    author=''
    category=''
    i=0
    def __init__(self, verbose = 0):
        fmt = formatter.AbstractFormatter(formatter.NullWriter())
        htmllib.HTMLParser.__init__(self, fmt, verbose)

    def datetime(self):
        return  apply(datetime.datetime,map((lambda x:int(x)),self.date.split('.')+self.time.split(':')))
    
    def start_div(self, attrs):
        if ('class','entry-body nerr') in attrs:
            self.is_content=True
            self.save_bgn()
    
    def end_div(self):
        if self.is_content:
            self.content=self.save_end()
        self.is_content=False
    
    def start_span(self , attrs):
        if ('class','pub-date') in attrs:
            self.is_date=True
            self.save_bgn()
        if ('class','pub-time') in attrs:
            self.is_time=True
            self.save_bgn()
    
    def end_span(self):
        if self.is_date:
            self.date=self.save_end()
        if self.is_time:
            self.time=self.save_end()
        self.is_date=False
        self.is_time=False

    def start_a(self, attrs):
        #print attrs
        if ('class','author') in attrs:
            #print attrs
            self.is_author=True
            self.save_bgn()
            #print attrs
        for name,value in attrs:
            if name == 'href' and value.startswith('http://wpshadow.bokee.com/cat'):
                self.save_bgn()
                self.is_category=True
         
    
    def end_a(self):
        if self.is_author and self.author=='':
            #print self.i
            self.author= self.save_end().replace("\n",'').strip()
        if self.is_category and self.category=='':
            #print self.i
            self.category= self.save_end().replace("\n",'').strip()
            
        self.is_author=False 
        self.is_category=False 
    def start_h2(self,attrs):
        self.save_bgn()
            #print data;

    def end_h2(self):
        self.title=self.save_end()
        
#    def handle_endtag(self, tag, attrs):
        
def main():
    lParser = BlogParser()
    text=open("viewdiary.41204139.html").read()
    lParser.feed(text)
    print lParser.title+"\n"+lParser.author+"\n"+lParser.category+"\n"+lParser.datetime().isoformat(" ")+"\n"+lParser.content

if __name__=='__main__':
    main()

